Page({
  /**
   * 页面的初始数据
   */
  data: {
    playlistId: "", // 歌单ID
    playlistDetail: {}, // 歌单详情
    tracks: [], // 歌曲列表
    isLoading: true, // 是否加载中
    isCollected: false, // 是否已收藏
    offset: 0, // 偏移量
    limit: 50, // 每次获取的歌曲数量
    hasMore: true, // 是否还有更多歌曲
    playMode: "list", // 播放模式: list(列表循环), single(单曲循环), random(随机播放)
    playModeIcon: "🔁", // 播放模式图标 (保留兼容性)
    playModeIconSrc: "play-in-order.png", // 播放模式图标图片
    // 播放状态相关
    nowPlaying: {
      id: null,
      title: "暂无播放",
      artist: "未知歌手",
      coverUrl: "",
    },
    isPlaying: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        playlistId: options.id,
      });

      // 设置页面标题
      if (options.name) {
        wx.setNavigationBarTitle({
          title: decodeURIComponent(options.name),
        });
      }

      // 获取歌单详情
      this.fetchPlaylistDetail();

      // 获取歌单中的歌曲
      this.fetchPlaylistTracks();

      // 获取保存的播放模式
      const savedPlayMode = wx.getStorageSync("playMode") || "list";
      this.setPlayModeIcon(savedPlayMode);
    } else {
      wx.showToast({
        title: "参数错误",
        icon: "none",
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 检查当前播放状态
    this.checkNowPlaying();
  },

  /**
   * 检查当前播放的歌曲
   */
  checkNowPlaying: function () {
    const app = getApp();
    const bgAudioManager = wx.getBackgroundAudioManager();

    // 检查当前是否有歌曲在播放
    const hasSong = bgAudioManager.src && bgAudioManager.src.length > 0;
    const isPlaying = hasSong && !bgAudioManager.paused;

    console.log(
      "当前播放状态:",
      hasSong ? "有歌曲" : "无歌曲",
      isPlaying ? "正在播放" : "已暂停"
    );

    // 从全局数据更新本地数据
    if (
      app.globalData &&
      app.globalData.nowPlaying &&
      app.globalData.nowPlaying.id
    ) {
      this.setData({
        nowPlaying: app.globalData.nowPlaying,
        isPlaying: isPlaying,
      });
    }

    // 注册播放状态变化回调
    app.playStatusCallback = (isPlaying) => {
      console.log("播放状态变化:", isPlaying ? "播放" : "暂停");
      this.setData({ isPlaying });
    };

    // 注册歌曲变化回调
    app.songChangeCallback = (song) => {
      console.log("歌曲变化:", song.title);
      this.setData({
        nowPlaying: song,
        isPlaying: true,
      });
    };
  },

  /**
   * 设置播放模式图标
   */
  setPlayModeIcon: function (mode) {
    let icon = "🔁"; // 默认列表循环
    let iconSrc = "play-in-order.png"; // 默认列表循环图标

    if (mode === "single") {
      icon = "🔂"; // 单曲循环
      iconSrc = "single-cycle.png"; // 单曲循环图标
    } else if (mode === "random") {
      icon = "🔀"; // 随机播放
      iconSrc = "random-play.png"; // 随机播放图标
    }

    this.setData({
      playMode: mode,
      playModeIcon: icon,
      playModeIconSrc: iconSrc,
    });

    // 保存播放模式到本地
    wx.setStorageSync("playMode", mode);

    // 更新全局播放模式
    const app = getApp();
    if (app.globalData) {
      app.globalData.playMode = mode;
    }
  },

  /**
   * 切换播放模式
   */
  changePlayMode: function () {
    const currentMode = this.data.playMode;
    let newMode = "list";

    // 循环切换：列表循环 -> 单曲循环 -> 随机播放 -> 列表循环
    if (currentMode === "list") {
      newMode = "single";
    } else if (currentMode === "single") {
      newMode = "random";
    }

    this.setPlayModeIcon(newMode);

    // 显示提示
    let modeText = "列表循环";
    if (newMode === "single") {
      modeText = "单曲循环";
    } else if (newMode === "random") {
      modeText = "随机播放";
    }

    wx.showToast({
      title: modeText,
      icon: "none",
      duration: 1500,
    });
  },

  /**
   * 获取歌单详情
   */
  fetchPlaylistDetail: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;

    wx.request({
      url: "https://smartsound.top/playlist/detail",
      method: "GET",
      data: {
        id: this.data.playlistId,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("歌单详情:", res.data);
        if (res.data && res.data.playlist) {
          // 处理歌单播放量
          let playCount = res.data.playlist.playCount;
          if (playCount > 10000) {
            playCount = (playCount / 10000).toFixed(1) + "万";
          }
          res.data.playlist.playCount = playCount;

          that.setData({
            playlistDetail: res.data.playlist,
            isCollected: res.data.playlist.subscribed || false,
          });
        }
      },
      fail(err) {
        console.error("获取歌单详情失败:", err);
        wx.showToast({
          title: "获取歌单详情失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 获取歌单中的歌曲
   */
  fetchPlaylistTracks: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;

    this.setData({ isLoading: true });

    wx.request({
      url: "https://smartsound.top/playlist/track/all",
      method: "GET",
      data: {
        id: this.data.playlistId,
        limit: this.data.limit,
        offset: this.data.offset,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("歌单歌曲:", res.data);
        if (res.data && res.data.songs) {
          // 合并已有的歌曲和新获取的歌曲
          const newTracks = that.data.tracks.concat(res.data.songs);
          const hasMore = res.data.songs.length === that.data.limit;

          that.setData({
            tracks: newTracks,
            offset: that.data.offset + that.data.limit,
            hasMore: hasMore,
            isLoading: false,
          });
        } else {
          that.setData({ isLoading: false });
        }
      },
      fail(err) {
        console.error("获取歌单歌曲失败:", err);
        that.setData({ isLoading: false });
        wx.showToast({
          title: "获取歌单歌曲失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 播放所有歌曲
   */
  playAll: function () {
    if (this.data.tracks.length === 0) {
      wx.showToast({
        title: "没有可播放的歌曲",
        icon: "none",
      });
      return;
    }

    // 播放第一首歌曲
    this.playSong({ currentTarget: { dataset: { index: 0 } } });
  },

  /**
   * 播放单首歌曲
   */
  playSong: function (e) {
    const index = e.currentTarget.dataset.index;
    const song = this.data.tracks[index];

    if (!song) return;

    const songId = song.id;
    const songName = song.name;

    // 获取全局app
    const app = getApp();

    // 准备歌曲信息
    const songInfo = {
      id: songId,
      name: songName,
      artist:
        (song.ar && song.ar[0].name) ||
        (song.artists && song.artists[0].name) ||
        "未知歌手",
      picUrl:
        (song.al && song.al.picUrl) || (song.album && song.album.picUrl) || "",
      album: (song.al && song.al.name) || (song.album && song.album.name) || "",
    };

    // 保存播放列表到全局
    app.globalData.currentSongList = [...this.data.tracks];
    app.globalData.currentSongIndex = index;

    // 确保歌曲时长信息存在
    if (!songInfo.dt && song.dt) {
      songInfo.dt = song.dt;
    } else if (!songInfo.dt && song.duration) {
      songInfo.dt = song.duration * 1000;
    }

    // 播放选中的歌曲 (使用全局app的playSong函数)
    app.playSong(songInfo);

    // 更新本地播放状态
    this.setData({
      nowPlaying: {
        id: songInfo.id,
        title: songInfo.name,
        artist: songInfo.artist,
        coverUrl: songInfo.picUrl,
      },
      isPlaying: true,
    });

    // 跳转到歌曲详情页
    wx.navigateTo({
      url: `/pages/song/song?id=${songId}&name=${encodeURIComponent(songName)}`,
    });
  },

  /**
   * 获取歌曲URL
   */
  fetchSongUrl: function (songId, callback) {
    const token = wx.getStorageSync("access_token");

    wx.request({
      url: "https://smartsound.top/song/url",
      method: "GET",
      data: {
        id: songId,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("歌曲URL:", res.data);
        if (res.data && res.data.data && res.data.data[0]) {
          const url = res.data.data[0].url;
          callback(url);
        } else {
          callback(null);
        }
      },
      fail(err) {
        console.error("获取歌曲URL失败:", err);
        callback(null);
      },
    });
  },

  /**
   * 切换收藏状态
   */
  toggleCollect: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;
    const t = this.data.isCollected ? 2 : 1; // 1: 收藏, 2: 取消收藏

    wx.request({
      url: "https://smartsound.top/playlist/subscribe",
      method: "GET",
      data: {
        id: this.data.playlistId,
        t: t,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        console.log("收藏操作结果:", res.data);
        if (res.data && res.data.code === 200) {
          that.setData({
            isCollected: !that.data.isCollected,
          });

          wx.showToast({
            title: that.data.isCollected ? "收藏成功" : "已取消收藏",
            icon: "success",
          });
        }
      },
      fail(err) {
        console.error("收藏操作失败:", err);
        wx.showToast({
          title: "操作失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 查看评论
   */
  viewComments: function () {
    wx.navigateTo({
      url: `/pages/comments/comments?id=${this.data.playlistId}&type=2`,
    });
  },

  /**
   * 处理正在播放栏点击
   */
  handleNowPlayingTap: function () {
    if (this.data.nowPlaying && this.data.nowPlaying.id) {
      // 跳转到歌曲详情页
      wx.navigateTo({
        url: `/pages/song/song?id=${
          this.data.nowPlaying.id
        }&name=${encodeURIComponent(this.data.nowPlaying.title)}`,
      });
    }
  },

  /**
   * 切换播放状态
   */
  togglePlayState: function (e) {
    // 阻止冒泡，防止触发父元素的点击事件
    if (e && typeof e.stopPropagation === "function") {
      e.stopPropagation();
    }

    console.log("触发播放/暂停按钮");

    // 获取全局app实例
    const app = getApp();

    // 获取背景音频管理器
    const bgAudioManager = wx.getBackgroundAudioManager();

    // 检查是否有正在播放的音频
    if (!bgAudioManager.src) {
      wx.showToast({
        title: "暂无播放歌曲",
        icon: "none",
        duration: 1500,
      });
      return;
    }

    // 根据当前播放状态执行相反操作
    const isCurrentlyPlaying = !bgAudioManager.paused;

    if (isCurrentlyPlaying) {
      // 当前在播放，执行暂停
      bgAudioManager.pause();
      this.setData({ isPlaying: false });

      // 同步全局状态
      if (app && app.globalData) {
        app.globalData.isPlaying = false;
      }
    } else {
      // 当前已暂停，执行播放
      bgAudioManager.play();
      this.setData({ isPlaying: true });

      // 同步全局状态
      if (app && app.globalData) {
        app.globalData.isPlaying = true;
      }
    }
  },

  /**
   * 分享歌单
   */
  sharePlaylist: function () {
    // 调用系统分享
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.hasMore && !this.data.isLoading) {
      this.fetchPlaylistTracks();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.playlistDetail.name || "精选歌单",
      path: `/pages/playlist/playlist?id=${
        this.data.playlistId
      }&name=${encodeURIComponent(this.data.playlistDetail.name || "")}`,
      imageUrl: this.data.playlistDetail.coverImgUrl,
    };
  },
});
